# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  before_filter :check_login, :check_authorization

  helper :all # include all helpers, all the time

  # See ActionController::RequestForgeryProtection for details
  # Uncomment the :secret if you're not using the cookie session store
  protect_from_forgery # :secret => '2f1bcaa616e21a5f299bcff4f7f9181c'
  
  # See ActionController::Base for details 
  # Uncomment this to filter the contents of submitted sensitive data parameters
  # from your application log (in this case, all fields with names like "password"). 
  filter_parameter_logging :password

  def check_login    
    @user = session[:user]    
    if @user.nil?
      flash[:notice] = "You must be logged in to access this resource."
      session[:requested_path] = request.path_parameters
      redirect_to :controller => 'login'
    end
  end

  def check_authorization 
    @is_authorized = true
    
    if @user
      case controller_name
      when UsersController.controller_name
        if ["index", "create", "destroy"].include? action_name
          @is_authorized = @user.admin?
        elsif ["update", "change_password", "update_password", "edit", "show"]
          @is_authorized = false unless (params[:id].to_i == @user.id) || @user.admin?
        else
          @is_authorized = false
        end
      end
    end

    unless @is_authorized
      flash[:notice] = "You are not authorized to perform this action: #{action_name} #{controller_name}"
      begin
        redirect_to :back
      rescue ActionController::RedirectBackError => e
        redirect_to root_path
      end
    end
  end

end
